package cn.iocoder.yudao.module.famous.doctor.controller.app.from;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.famous.doctor.controller.app.from.constants.ProjectRedisKeyConstants;
import cn.iocoder.yudao.module.famous.doctor.controller.app.from.vo.OperateProjectItemVO;
import cn.iocoder.yudao.module.famous.doctor.controller.app.from.vo.request.OperateProjectItemRequest;
import cn.iocoder.yudao.module.famous.doctor.controller.app.from.vo.request.QueryProjectItemRequest;
import cn.iocoder.yudao.module.famous.doctor.controller.app.from.vo.request.SortProjectItemRequest;
import cn.iocoder.yudao.module.famous.doctor.controller.app.operator.vo.OperatorPerformanceHead;
import cn.iocoder.yudao.module.famous.doctor.dal.dataobject.form.UserProjectItemEntity;
import cn.iocoder.yudao.module.famous.doctor.dal.dataobject.struct.ItemDefaultValueStruct;
import cn.iocoder.yudao.module.famous.doctor.dal.mysql.operator.OperatorPerformanceHeadMapper;
import cn.iocoder.yudao.module.famous.doctor.service.forimRecord.UserProjectItemService;
import cn.iocoder.yudao.module.famous.doctor.utils.JsonUtils;
import cn.iocoder.yudao.module.famous.doctor.utils.SortUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 表单项
 *
 * @author wyx
 * @since 2021-08-10
 */
@Validated
@RestController
@RequestMapping("/manager/from/item")
@Tag(name = "表单项")
public class FromItemController {
	@Autowired
	private UserProjectItemService projectItemService;
	@Autowired
	private SortUtils sortUtils;
	@Autowired
	private OperatorPerformanceHeadMapper operatorPerformanceHeadMapper;
	/**
	 * 项目表单项查询
	 */
	@Operation(summary ="项目表单项查询")
	@GetMapping("/list")
	public CommonResult queryProjectItem(QueryProjectItemRequest request) {
//		ValidatorUtils.validateEntity(request);
		List<UserProjectItemEntity> itemEntityList = projectItemService.list(Wrappers.<UserProjectItemEntity>lambdaQuery()
				.eq(UserProjectItemEntity::getProjectKey, request.getKey())
				.eq(ObjectUtil.isNotNull(request.getDisplayType()), UserProjectItemEntity::getDisplayType, request.getDisplayType())
				.orderByAsc(UserProjectItemEntity::getSort)
		);
		return success(itemEntityList);
	}


	/**
	 * 项目表单项创建
	 *
	 * @param request
	 */
//	@Login
	@Operation(summary ="项目表单项创建")
	@PostMapping("/create")
	public CommonResult createProjectItem(@RequestBody OperateProjectItemRequest request) {
//		ValidatorUtils.validateEntity(request, AddGroup.class);
		UserProjectItemEntity entity = formatProjectItem(request);
		//排序下标计算
		entity.setSort(sortUtils.getInitialSortPosition(
				StrUtil.format(ProjectRedisKeyConstants.PROJECT_ITEM_POS_DELTA, request.getProjectKey())));
		boolean save = projectItemService.save(entity);
		return success(new OperateProjectItemVO(entity.getSort(), entity.getId(), save));
	}

	@Operation(summary ="项目表单项数组保存")
	@PostMapping("/createProjectItems")
	public CommonResult<List<UserProjectItemEntity>> createProjectItems(@RequestBody List<OperateProjectItemRequest> request) {
//		ValidatorUtils.validateEntity(request, AddGroup.class);
		List<UserProjectItemEntity> list = new ArrayList<>();
		for (OperateProjectItemRequest operateProjectItemRequest : request) {
			UserProjectItemEntity entity = formatProjectItem(operateProjectItemRequest);
			//排序下标计算
//			entity.setSort(sortUtils.getInitialSortPosition(
//					StrUtil.format(ProjectRedisKeyConstants.PROJECT_ITEM_POS_DELTA, operateProjectItemRequest.getProjectKey())));
			list.add(entity);
		}
		projectItemService.saveOrUpdateBatch(list);
		return success(list);
	}

	/**
	 * 格式化项目Item的数据
	 */
	private UserProjectItemEntity formatProjectItem(OperateProjectItemRequest request) {
		//把Map转换成Bean 在转换成Map 去除不在bean字段列表的多字段
		Object bean = BeanUtil.toBeanIgnoreCase(request.getExpand(), request.getType().getExpandClass(), false);
		UserProjectItemEntity entity = new UserProjectItemEntity();
		BeanUtil.copyProperties(request, entity, UserProjectItemEntity.Fields.defaultValue);
		entity.setExpand(BeanUtil.beanToMap(bean));
		//默认值格式化 1判断是否是Json
		Object defaultValue = request.getDefaultValue();
		if (ObjectUtil.isNotEmpty(defaultValue)) {
			boolean json = JSONUtil.isJson(JsonUtils.objToJson(request.getDefaultValue()));
			if (json) {
				entity.setDefaultValue(new ItemDefaultValueStruct(true, JsonUtils.objToJson(request.getDefaultValue())));
			}
		}
		entity.setDefaultValue(new ItemDefaultValueStruct(false, defaultValue));
		return entity;
	}


	/**
	 * 表单项更新
	 *
	 * @param request
	 */
//	@Login
	@Operation(summary ="表单项更新")
	@PostMapping("/update")
	public CommonResult updateProjectItem(@RequestBody OperateProjectItemRequest request) {

//		ValidatorUtils.validateEntity(request, UpdateGroup.class);
		boolean update = projectItemService.update(formatProjectItem(request), Wrappers.<UserProjectItemEntity>lambdaQuery()
				.eq(UserProjectItemEntity::getProjectKey, request.getProjectKey())
				.eq(UserProjectItemEntity::getFormItemId, request.getFormItemId()));


//		String projectKey = request.getProjectKey();
//		OperatorPerformanceHead operatorPerformanceHead = operatorPerformanceHeadMapper.selectOne(new LambdaQueryWrapper<OperatorPerformanceHead>()
//				.eq(OperatorPerformanceHead::getTemplateKey, projectKey));
//		//添加新表单
//		String uuid = IdUtil.fastSimpleUUID();
//		operatorPerformanceHead.setKey(uuid);
//		operatorPerformanceHeadMapper.insert(operatorPerformanceHead);
//
//		//表单项添加
//		UserProjectItemEntity userProjectItemEntity = formatProjectItem(request);
//		userProjectItemEntity.setProjectKey(uuid);
//		projectItemService.save(userProjectItemEntity);

		return success(update);
	}


	/**
	 * 表单项删除
	 */
//	@Login
	@Operation(summary ="表单项删除")
	@DeleteMapping("/delete")
	public CommonResult<Boolean> deleteProjectItem(Long id) {
//		ValidatorUtils.validateEntity(request, OperateProjectItemRequest.DeleteGroup.class);
//		boolean delete = projectItemService.remove(Wrappers.<UserProjectItemEntity>lambdaQuery()
//				.eq(UserProjectItemEntity::getProjectKey, request.getProjectKey())
//				.eq(UserProjectItemEntity::getFormItemId, request.getFormItemId())
//				.eq(UserProjectItemEntity::getType, request.getType()));
		boolean delete = projectItemService.removeById(id);
		return success(delete);
	}

	/**
	 * 表单项排序
	 *
	 * @param request
	 */
//	@Login
	@Operation(summary ="表单项排序")
	@PostMapping("/sort")
	public CommonResult<OperateProjectItemVO> sortProjectItem(@RequestBody SortProjectItemRequest request) {
//		ValidatorUtils.validateEntity(request);
		if (ObjectUtil.isNull(request.getAfterPosition())
				&& ObjectUtil.isNull(request.getBeforePosition())) {
			return success(null);
		}
		UserProjectItemEntity itemEntity = projectItemService.getOne(Wrappers.<UserProjectItemEntity>lambdaQuery()
				.eq(UserProjectItemEntity::getProjectKey, request.getProjectKey())
				.eq(UserProjectItemEntity::getFormItemId, request.getFormItemId())
				.last("limit 1"));
		Long sort = sortUtils.calcSortPosition(request.getBeforePosition(), request.getAfterPosition());
		itemEntity.setSort(sort);
		boolean b = projectItemService.updateById(itemEntity);
		return success(new OperateProjectItemVO(itemEntity.getSort(), itemEntity.getId(), b));
	}

}
